
TOOL.Category = '(Shanjaq)'
TOOL.Name = '#Storage Devices'
TOOL.Command = nil
TOOL.ConfigName = ''

TOOL.ClientConVar['type'] = 'air_tank'

TOOL.ClientConVar['model'] = 'models/props_c17/canister01a.mdl'

cleanup.Register('storagedevice')
cleanup.Register( 'tankconstraints' )


if ( CLIENT ) then
	language.Add( 'Tool_receptacles_name', 'Energy Systems (Shanjaq)' )
	language.Add( 'Tool_receptacles_desc', 'Create Storage Devices attached to any surface.' )
	language.Add( 'Tool_receptacles_0', 'Left-Click: Spawn a Device.  Right-Click: Repair Device.' )

	language.Add( 'Undone_StorageDevice', 'Storage Device Undone' )
	language.Add( 'Undone_Hose', 'Conduit Undone' )
	language.Add( 'Cleanup_airtanks', 'Storage System' )
	language.Add( 'Cleaned_airtank', 'Cleaned up all Storage Devices' )
	language.Add( 'SBoxLimit_receptacles', 'Maximum Storage Devices Reached' )
end

if ( GAMEMODE.Name == "SpaceBuild" || SpaceBuild ) then 
	receptacle_models = {
		{ 'Small Air Tank', 'models/props_c17/canister01a.mdl', 'air_tank' },
		{ 'Large Air Tank', 'models/props_c17/canister_propane01a.mdl', 'air_tank' },
		{ 'Hydrogen Tank', 'models/props_c17/canister02a.mdl', 'hydrogen_tank' },
		{ 'Mass Hydrogen Tank', 'models/props_wasteland/coolingtank02.mdl', 'hydrogen_tank' },
		{ 'Small Coolant Tank', 'models/props_junk/PropaneCanister001a.mdl', 'coolant_tank' },
		{ 'Large Coolant Tank', 'models/props_borealis/bluebarrel001.mdl', 'coolant_tank' },
		{ 'Small Energy Cell', 'models/Items/car_battery01.mdl', 'energy_cell' },
		{ 'Large Energy Cell', 'models/props_c17/substation_stripebox01a.mdl', 'energy_cell' },
		{ 'Small Resource Cache', 'models/props_lab/powerbox01a.mdl', 'res_cache' },
		{ 'Large Resource Cache', 'models/props_c17/substation_transformer01a.mdl', 'res_cache' }
	}
else
	receptacle_models = {
		{ 'Small Air Tank', 'models/props_c17/canister01a.mdl', 'air_tank' },
		{ 'Large Air Tank', 'models/props_c17/canister_propane01a.mdl', 'air_tank' },
		{ 'Hydrogen Tank', 'models/props_c17/canister02a.mdl', 'hydrogen_tank' },
		{ 'Mass Hydrogen Tank', 'models/props_wasteland/coolingtank02.mdl', 'hydrogen_tank' },
		{ 'Small Coolant Tank', 'models/props_junk/PropaneCanister001a.mdl', 'coolant_tank' },
		{ 'Large Coolant Tank', 'models/props_borealis/bluebarrel001.mdl', 'coolant_tank' },
		{ 'Small Energy Cell', 'models/Items/car_battery01.mdl', 'energy_cell' },
		{ 'Large Energy Cell', 'models/props_c17/substation_stripebox01a.mdl', 'energy_cell' },
		{ 'Small Resource Cache', 'models/props_lab/powerbox01a.mdl', 'res_cache' },
		{ 'Large Resource Cache', 'models/props_c17/substation_transformer01a.mdl', 'res_cache' }
	}
end

--models/props/de_nuke/fuel_cask.mdl
--models/props_citizen_tech/Firetrap_PropaneCanister01a.mdl
--models/props/de_nuke/coolingtank.mdl
--models/props/de_nuke/storagetank.mdl
--models/props/de_train/Processor_NoBase.mdl
--models/props/de_train/de_train_signalbox_01.mdl
--models/props/de_prodigy/transformer.mdl
--models/props_combine/combine_light002a.mdl
function TOOL:LeftClick( trace )
	if trace.Entity && (trace.Entity:IsPlayer() ) then return false end
	
	if(CLIENT) then
		return true
	end

	if(!SERVER) then return false end

	if ( !self:GetSWEP():CheckLimit( "receptacles" ) ) then return false end

	local receptacle_type		= self:GetClientInfo('type')
	local receptacle_model	= self:GetClientInfo('model')
	
	local ply = self:GetOwner()
	local Pos = trace.HitPos
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	ent = MakeStorageDevice( ply, Ang, Pos, receptacle_type, receptacle_model )
	ent:SetPos( trace.HitPos - trace.HitNormal * ent:OBBMins().z)
	
	
	if ( trace.Entity:IsValid() ) then
		local const = constraint.Weld(ent, trace.Entity,0, trace.PhysicsBone, 0, systemmanager )
		nocollide = constraint.NoCollide( ent, trace.Entity, 0, trace.PhysicsBone )
		trace.Entity:DeleteOnRemove( ent )
	end

	undo.Create('StorageDevice')
		undo.AddEntity( ent)
		undo.AddEntity( const )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()


	ply:AddCleanup( 'storagedevice', const )
	ply:AddCleanup( 'storagedevice', nocollide )
	
	return true
end



function TOOL:RightClick( trace )
	if (not trace.Entity:GetTable().Repair) then
        self:GetOwner():SendLua( "GAMEMODE:AddNotify('Object cannot be repaired!', NOTIFY_GENERIC, 7);" )
		return
	end
	trace.Entity:Repair()
	return true
end


function TOOL:Reload(trace)
	return true
end




if SERVER then 
    CreateConVar('sbox_maxreceptacles',24)
	
	function MakeStorageDevice( ply, Ang, Pos, receptacle_type, model )
		if ( !ply:CheckLimit( "receptacles" ) ) then return nil end
		if not ( RES_DISTRIB == 1 ) then
			ply:PrintMessage( HUD_PRINTCENTER, "Please Install Resource Distribution Addon.\nThis mod requires it to function.\nSearch GarrysMod.org for 'distribution'" )  
			return
		end
		local ent = ents.Create( receptacle_type )
			if !ent:IsValid() then return false end
			ent:SetModel( model )
			ent:SetAngles(Ang)
			ent:SetPos(Pos)
		ent:Spawn()

		ent:SetVar('Owner',ply)
		
		local phys = ent:GetPhysicsObject()
		local max_health = 0
		local NextThink = CurTime() +  1
		if ( receptacle_type == "air_tank" ) then
			if ( model == "models/props_c17/canister01a.mdl" ) then
				max_health = 200
				if (phys:IsValid()) then phys:SetMass(20) end
				RD_AddResource(ent, "air", 6000)
			elseif ( model == "models/props_c17/canister_propane01a.mdl" ) then
				max_health = 300
				if (phys:IsValid()) then phys:SetMass(200) end
				RD_AddResource(ent, "air", 12000)
			end
			local rtable = {
				receptacle_type = receptacle_type,
				model = model,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'air_tank', MakeStorageDevice,  'Ang', 'Pos', 'receptacle_type', 'model' )
		elseif ( receptacle_type == "hydrogen_tank" ) then
			if ( model == "models/props_c17/canister02a.mdl" ) then
				max_health = 200
				if (phys:IsValid()) then phys:SetMass(20) end
				RD_AddResource(ent, "hydrogen", 6000)
			elseif ( model == "models/props_wasteland/coolingtank02.mdl" ) then
				max_health = 450
				if (phys:IsValid()) then phys:SetMass(500) end
				RD_AddResource(ent, "hydrogen", 50000)
			end
			local rtable = {
				receptacle_type = receptacle_type,
				model = model,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
			table.Merge(ent:GetTable(), rtable )
		elseif ( receptacle_type == "coolant_tank" ) then
			if (model == "models/props_junk/PropaneCanister001a.mdl") then
				max_health = 200
				if (phys:IsValid()) then phys:SetMass(20) end
				RD_AddResource(ent, "coolant", 4000)
			elseif (model == "models/props_borealis/bluebarrel001.mdl") then
				max_health = 300
				if (phys:IsValid()) then phys:SetMass(200) end
				RD_AddResource(ent, "coolant", 12000)
			end
			local rtable = {
				receptacle_type = receptacle_type,
				model = model,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'coolant_tank', MakeStorageDevice,  'Ang', 'Pos', 'receptacle_type', 'model' )
			
		elseif ( receptacle_type == "energy_cell" ) then
			if (model == "models/Items/car_battery01.mdl") then
				max_health = 200
				if (phys:IsValid()) then phys:SetMass(20) end
				RD_AddResource(ent, "energy", 4000)
			elseif (model == "models/props_c17/substation_stripebox01a.mdl") then
				max_health = 700
				if (phys:IsValid()) then phys:SetMass(1000) end
				RD_AddResource(ent, "energy", 50000)
			end
			local rtable = {
				receptacle_type = receptacle_type,
				model = model,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'energy_cell', MakeStorageDevice,  'Ang', 'Pos', 'receptacle_type', 'model' )
			
		elseif ( receptacle_type == "res_cache" ) then
			if (model == "models/props_lab/powerbox01a.mdl") then
				max_health = 400
				if (phys:IsValid()) then phys:SetMass(150) end
				RD_AddResource(ent, "air", 6000)
				RD_AddResource(ent, "energy", 6000)
				RD_AddResource(ent, "coolant", 6000)
				RD_AddResource(ent, "hydrogen", 6000)
			elseif (model == "models/props_c17/substation_transformer01a.mdl") then
				max_health = 1200
				if (phys:IsValid()) then phys:SetMass(2000) end
				RD_AddResource(ent, "air", 24000)
				RD_AddResource(ent, "energy", 24000)
				RD_AddResource(ent, "coolant", 24000)
				RD_AddResource(ent, "hydrogen", 24000)
			end
			local rtable = {
				receptacle_type = receptacle_type,
				model = model,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'energy_cell', MakeStorageDevice,  'Ang', 'Pos', 'receptacle_type', 'model' )
			
		end
		
			
		if ent:GetTable().OnTakeDamage then
			local Prev = ent:GetTable().OnTakeDamage
			
			function ent:OnTakeDamage(Info)
				DamageLS(self, Info:GetDamage())
				Prev(self, Info)
			end
		end
			
		ply:AddCount('receptacles', ent)
		
		return ent
	end
	duplicator.RegisterEntityClass("air_tank", MakeStorageDevice, "Ang", "Pos", "receptacle_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("hydrogen_tank", MakeStorageDevice, "Ang", "Pos", "receptacle_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("energy_cell", MakeStorageDevice, "Ang", "Pos", "receptacle_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("coolant_tank", MakeStorageDevice, "Ang", "Pos", "receptacle_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("res_cache", MakeStorageDevice, "Ang", "Pos", "receptacle_type", "model", "Vel", "aVel", "frozen")
end

function TOOL.BuildCPanel( cp )
	cp:AddControl( 'Header', { Text = '#Tool_receptacles_name', Description	= '#Tool_receptacles_desc' }  )

	local combo = {}
	combo.Label = 'Life Support Device'
	combo.MenuButton = 1
	combo.Folder = 'settings/menu/main/construct/receptacles/'
	combo.Options = {}
	
	for k, v in pairs(receptacle_models) do
		combo.Options[v[1]] = { receptacles_model = v[2], receptacles_type = v[3] }
	end

	cp:AddControl('ComboBox', combo) 

end

function TOOL:UpdateGhostStorageDevice( ent, player )

	if ( !ent ) then return end
	if ( !ent:IsValid() ) then return end

	local tr 	= utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
	local trace 	= util.TraceLine( tr )
	if (!trace.Hit) then return end
	
--	if (trace.Entity && trace.Entity:GetClass() == "air_tank" || trace.Entity:IsPlayer() ) then
	if ( trace.Entity:IsPlayer() ) then
	
		ent:SetNoDraw( true )
		return
		
	end
	local Ang = trace.HitNormal:Angle()
	
	local min = ent:OBBMins()
	local Pos = trace.HitPos
	Ang.pitch = Ang.pitch + 90
	ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
	ent:SetAngles( Ang )
	
	ent:SetNoDraw( false )
	
end


function TOOL:Offset( ang, offsetvec )
	local offset = offsetvec
	local stackdir = ang:Up()
	
	offset = ang:Up() * offset.X + ang:Forward() * -1 * offset.Z + ang:Right() * offset.Y

	return stackdir * 2 + offset
end


function TOOL:Think()
	local model	= self:GetClientInfo('model')
	local rtype = self:GetClientInfo('type')
	
	if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model) then
		self:MakeGhostEntity( model, Vector(0,0,0), Angle(0,0,0) )
	end
	self:UpdateGhostStorageDevice( self.GhostEntity, self:GetOwner() )
end


